package org.wattdepot.gdata.kukuicup.updater.powermeter;

import java.util.Timer;
import java.util.TimerTask;
import org.wattdepot.gdata.kukuicup.service.GDataService;
import org.wattdepot.gdata.kukuicup.service.WattDepotService;
import org.wattdepot.gdata.kukuicup.updater.Updater;

/**
 * Implements the PowerMeter Updater, which creates individual timer tasks for
 * each source that run once every few seconds and updates the spreadsheet with the most
 * recent power value for that source.
 * @author Philip Johnson
 */
public class PowerMeterUpdater extends Updater {
  
  /** The property in the kukuicup.gdata.properties file indicating how often to update power. */
  private String updateIntervalProperty = "power.meter.update.interval";
  
  /** The default interval for the power updates if not otherwise specified. */
  private int defaultUpdateInterval = 15;
  
  /**
   * Creates this updater, initializing the various services. 
   * @param wattDepotService The wattdepot service. 
   * @param gdataService The gdata service.
   * @throws Exception If problems occur initializing these services.  
   */
  public PowerMeterUpdater(WattDepotService wattDepotService, GDataService gdataService) 
  throws Exception {
    super("PowerMeter", wattDepotService, gdataService);
  }


  /**
   * This task generates a separate TimerTask for each source in the spreadsheet. 
   * Each TimerTask runs every N seconds, gets the most recent power sensor data for
   * its source, then writes out that data value to the spreadsheet.
   * N depends upon the power.meter.update.interval property.
   */
  @Override
  public void run() {
    // Get the update interval for getting the current power.
    int updateInterval = this.wattDepotService.getProperties()
    .getIntegerProperty(updateIntervalProperty, defaultUpdateInterval);
    System.out.format("Updating PowerMeter spreadsheet at %s second intervals%n", updateInterval);

    // We space out these tasks to avoid overloading WattDepot. 
    int delay = 0;

    for (String sourceName : sourceNames) {
      Timer timer = new Timer();
      TimerTask task = new PowerMeterTask(wattDepotService, gdataService, 
          spreadsheetURL, sourceName, isVirtual(sourceName), getRow(sourceName));
      int updateIntervalMillis = 1000 * updateInterval;
      timer.schedule(task, delay, updateIntervalMillis);
      // space out these tasks by 10 seconds so they don't hit the WattDepot all at once.  
      delay += 1000 * 10;
      timers.add(timer);
    }
  }


}
